﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using MongoDB.Driver;
using System.Configuration;

namespace MvcDemo.Move.Models.DBUtility
{
    /// <summary>
    /// 不存在的数据库和集合都不会执行
    /// </summary>
    public class MongoDBHelper
    {
        #region
        public static readonly string MongoDB_Server_Address = ConfigurationManager.ConnectionStrings["MongoDB"].ToString();

        protected static MongoServer GetServer(string connString)
        {
            #region
            //MongoServer.Create("mongodb://192.168.1.201:39100,192.168.1.202:39100,192.168.1.203:39100");
            //return MongoServer.Create(mongoServerSettings);
            //server=192.168.1.201:39100,192.168.1.202:39100;database=database;connect=direct
            var builder = new MongoConnectionStringBuilder(MongoDB_Server_Address);

            var server = MongoServer.Create(builder);
            //if (!string.IsNullOrEmpty(builder.DatabaseName) && server.DatabaseExists(builder.DatabaseName) == false)
            //{
            //    return MongoServer.Create();
            //}
            return server;
            #endregion
        }

        protected static MongoDatabase GetDatabase(string name)
        {
            #region
            var mongoServer = GetServer(MongoDB_Server_Address);
            if (mongoServer.DatabaseExists(name) == false)
            {
                return null;
            }
            return mongoServer[name];
            #endregion
        }

        /// <summary>
        /// 数据库和表名返回MongoColl;
        /// </summary>
        /// <param name="databaseName">注意名字大小写</param>
        /// <param name="tableName">注意名字大小写</param>
        /// <returns></returns>
        public static MongoCollection<MongoDB.Bson.BsonDocument> GetCollection(string databaseName, string tableName)
        {
            #region
            var database = GetDatabase(databaseName);
            if (database == null || database.CollectionExists(tableName) == false)
            {
                return null;
            }

            return database[tableName];
            #endregion
        }
        #endregion
    }
}